package cl.xintec.utils
{
	public class DateUtil
	{		
		public function DateUtil() {
		}

	    public static function stringToDate(valueString:String):Date {
	    	if (valueString == null) {
	    		return null;
	    	}
	    	if (valueString == "17530101000000000") {
	    		return null;
	    	}	    	
	    	if (valueString.length != 17) {
	    		return null;
	    	}

	    	var ano:Number;
	    	var mes:Number;
	    	var dia:Number;
	    	var hor:Number;
	    	var min:Number;
	    	var seg:Number;
	    	var mil:Number;

			ano = new Number(valueString.substr(0, 4));
			mes = new Number(valueString.substr(4, 2));
			dia = new Number(valueString.substr(6, 2));
			hor = new Number(valueString.substr(8, 2));
			min = new Number(valueString.substr(10, 2));
			seg = new Number(valueString.substr(12, 2));
			mil = new Number(valueString.substr(14, 3));

			var date:Date = new Date(ano, mes - 1, dia, hor, min, seg, mil);
			return date;
	    }

	    public static function dateTostring(valueDate:Date):String {
	    	if (valueDate == null) {
	    		return "17530101000000000";
	    	}

	    	var ano:Number;
	    	var mes:Number;
	    	var dia:Number;
	    	var hor:Number;
	    	var min:Number;
	    	var seg:Number;
	    	var mil:Number;

			ano = valueDate.getFullYear();
			mes = valueDate.getMonth();
			dia = valueDate.getDate();
			hor = valueDate.getHours();
			min = valueDate.getMinutes();
			seg = valueDate.getSeconds();
			mil = valueDate.getMilliseconds();

			var date:String = new String(ano)
			                + leftZeros(new String(mes + 1), 2)
			                + leftZeros(new String(dia), 2)
			                + leftZeros(new String(hor), 2)
			                + leftZeros(new String(min), 2)
			                + leftZeros(new String(seg), 2)
			                + leftZeros(new String(mil), 3);
			return date;
	    }

	    private static function leftZeros(value:String, zeros:int):String {
	    	if (value == null) {
	    		return null;
	    	}
	    	for (var i:int = 0; i < zeros; i++) {
	    		value = "0" + value;
	    	}
	    	value = value.substr(value.length - zeros, zeros);
	    	return value;
	    }
	}
}